import * as THREE from 'three';

/**
 * 创建中国地图3D模型
 */
export const createChinaMap = async (scene, getProvinceSalesData, getColorByAmount) => {
  // 清除场景中的现有对象
  while(scene.children.length > 0) { 
    const object = scene.children[0];
    if(object.type === 'Group' || object.type === 'Mesh') {
      scene.remove(object);
    } else {
      break;
    }
  }

  // 创建提示框DOM元素
  const tooltip = document.createElement('div');
  tooltip.id = 'province-tooltip';
  tooltip.style.cssText = `
    position: fixed;
    z-index: 9999;
    background-color: rgba(1, 18, 71, 0.9);
    border: 2px solid #00ffff;
    border-radius: 8px;
    padding: 12px 15px;
    box-shadow: 0 0 15px rgba(0, 255, 255, 0.5);
    min-width: 200px;
    color: white;
    pointer-events: none;
    display: none;
  `;
  document.body.appendChild(tooltip);

  // 加载中国地图GeoJSON数据
  const response = await fetch('/中华人民共和国.json');
  const geoData = await response.json();
  
  if (!geoData || !geoData.features) {
    console.error('无效的GeoJSON数据');
    return null;
  }
  
  // 创建包含所有省份的组
  const chinaGroup = new THREE.Group();
  chinaGroup.rotation.x = -Math.PI / 2; // 水平放置
  
  // 用于计算地图中心和边界的变量
  let centerX = 0, centerY = 0, pointCount = 0;
  let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;
  
  // 处理GeoJSON数据创建省份几何体
  processGeoData(geoData, chinaGroup, (point) => {
    // 更新中心点计算和边界
    if (point.length >= 2 && isFinite(point[0]) && isFinite(point[1])) {
      centerX += point[0];
      centerY += point[1];
      pointCount++;
      
      // 更新边界
      minX = Math.min(minX, point[0]);
      maxX = Math.max(maxX, point[0]);
      minY = Math.min(minY, point[1]);
      maxY = Math.max(maxY, point[1]);
    }
  }, getProvinceSalesData, getColorByAmount);
  
  // 计算实际中心点和尺寸
  if (pointCount > 0) {
    centerX /= pointCount;
    centerY /= pointCount;
  }
  
  // 计算地图尺寸和调整缩放
  const size = Math.max(maxX - minX, maxY - minY);
  const scaleFactor = 35 / size;
  
  // 调整所有省份位置
  chinaGroup.children.forEach((provinceGroup) => {
    provinceGroup.position.set(-centerX, -centerY, 0);
  });
  
  // 调整地图缩放和位置
  chinaGroup.scale.set(scaleFactor, scaleFactor, scaleFactor);
  
  // 确保地图位于场景中心
  chinaGroup.position.set(0, 0, 0);
  
  // 将地图添加到场景中
  scene.add(chinaGroup);
  
  return chinaGroup;
};

/**
 * 处理GeoJSON数据
 */
const processGeoData = (geoData, chinaGroup, updateBoundsFn, getProvinceSalesData, getColorByAmount) => {
  // 创建一个集合来跟踪已处理的省份
  const processedProvinces = new Set();
  
  geoData.features.forEach((province) => {
    if (!province.geometry || !province.properties?.name) return;
    
    const provinceName = province.properties.name;
    
    // 检查是否已处理过该省份
    if (processedProvinces.has(provinceName)) {
      console.warn(`省份${provinceName}已被处理过，跳过重复处理`);
      return;
    }
    
    // 标记该省份已处理
    processedProvinces.add(provinceName);
    
    // 创建省份组
    const provinceGroup = new THREE.Group();
    provinceGroup.name = provinceName;
    
    // 获取该省份的销售数据
    const salesData = getProvinceSalesData(provinceName);
    
    // 处理几何类型
    if (province.geometry.type === 'Polygon') {
      processPolygon(province.geometry.coordinates[0], provinceGroup, updateBoundsFn, salesData, getColorByAmount);
    } 
    else if (province.geometry.type === 'MultiPolygon') {
      province.geometry.coordinates.forEach(polygon => {
        processPolygon(polygon[0], provinceGroup, updateBoundsFn, salesData, getColorByAmount);
      });
    }
    
    // 将省份添加到中国组
    if (provinceGroup.children.length > 0) {
      chinaGroup.add(provinceGroup);
    }
  });
};

/**
 * 处理单个多边形
 */
const processPolygon = (outerRing, provinceGroup, updateBoundsFn, salesData, getColorByAmount) => {
  if (!Array.isArray(outerRing) || outerRing.length < 3) return;
  
  // 更新边界
  outerRing.forEach(updateBoundsFn);
  
  // 创建形状
  const shape = new THREE.Shape();
  let firstValid = true;
  
  for (let i = 0; i < outerRing.length; i++) {
    const point = outerRing[i];
    if (point.length >= 2 && isFinite(point[0]) && isFinite(point[1])) {
      if (firstValid) {
        shape.moveTo(point[0], point[1]);
        firstValid = false;
      } else {
        shape.lineTo(point[0], point[1]);
      }
    }
  }
  
  // 创建省份几何体
  if (!firstValid) { // 确保至少有一个有效点
    createProvinceGeometry(shape, provinceGroup, salesData, getColorByAmount);
  }
};

/**
 * 创建省份几何体
 */
const createProvinceGeometry = (shape, group, salesData, getColorByAmount) => {
  if (!shape || shape.curves.length === 0) return;
  
  // 增加地图厚度
  const height = 2.5; // 增加厚度
  
  const geometry = new THREE.ExtrudeGeometry(shape, {
    depth: height,
    bevelEnabled: false,
    curveSegments: 4, // 减少曲线分段，提高性能
    UVGenerator: THREE.ExtrudeGeometry.WorldUVGenerator // 确保UV映射正确
  });
  
  // 检查几何体有效性
  if (geometry.attributes.position.count === 0) return;
  
  // 根据销售额确定颜色
  let baseColor;
  if (salesData && salesData.salesAmount !== undefined) {
    baseColor = getColorByAmount(salesData.salesAmount);
  } else {
    // 使用默认青色
    baseColor = new THREE.Color(0x3C7EBB);
  }
  
  // 创建省份主体材质
  const material = new THREE.MeshPhongMaterial({
    color: baseColor,
    transparent: false, // 移除透明效果
    shininess: 50, // 降低光泽度
    emissive: baseColor.clone().multiplyScalar(0.1), // 降低发光强度
    emissiveIntensity: 0.1,
    specular: new THREE.Color(0x111111) // 降低高光强度
  });
  
  // 创建高亮材质
  const highlightMaterial = new THREE.MeshPhongMaterial({
    color: 0xFFFFFF,
    transparent: false,
    shininess: 100,
    emissive: baseColor.clone().multiplyScalar(0.5),
    emissiveIntensity: 0.5,
    specular: new THREE.Color(0xFFFFFF)
  });
  
  // 创建省份主体
  const mesh = new THREE.Mesh(geometry, material);
  
  mesh.receiveShadow = true;
  mesh.castShadow = true;
  
  // 存储省份数据用于交互
  if (salesData) {
    mesh.userData = {
      provinceName: group.name,
      salesAmount: salesData.salesAmount,
      orderCount: salesData.orderCount,
      productCount: salesData.productCount,
      originalMaterial: material,
      highlightMaterial: highlightMaterial
    };
  } else {
    mesh.userData = {
      provinceName: group.name,
      originalMaterial: material,
      highlightMaterial: highlightMaterial
    };
  }
  
  group.add(mesh);
  
  // 添加边框
  const edges = new THREE.LineSegments(
    new THREE.EdgesGeometry(geometry),
    new THREE.LineBasicMaterial({
      color: 0x00ffff,
      transparent: false,
      opacity: 0.8
    })
  );
  group.add(edges);
}; 